#!/usr/bin/python3
"""
(This problem is the same as Minimize Malware Spread, with the differences
bolded.)

In a network of nodes, each node i is directly connected to another node j if
and only if graph[i][j] = 1.

Some nodes initial are initially infected by malware.  Whenever two nodes are
directly connected and at least one of those two nodes is infected by malware,
both nodes will be infected by malware.  This spread of malware will continue
until no more nodes can be infected in this manner.

Suppose M(initial) is the final number of nodes infected with malware in the
entire network, after the spread of malware stops.

We will remove one node from the initial list, completely removing it and any
connections from this node to any other node.  Return the node that if removed,
would minimize M(initial).  If multiple nodes could be removed to minimize
M(initial), return such a node with the smallest index.

Example 1:
Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output: 0

Example 2:
Input: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]
Output: 1

Example 3:
Input: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]
Output: 1


Note:
1 < graph.length = graph[0].length <= 300
0 <= graph[i][j] == graph[j][i] <= 1
graph[i][i] = 1
1 <= initial.length < graph.length
0 <= initial[i] < graph.length
"""
from typing import List
from collections import defaultdict


class DisjointSet:
    def __init__(self):
        self.pi = {}

    def union(self, x, y):
        self.pi[self.find(x)] = self.find(y)

    def find(self, x):
        if x not in self.pi:
            self.pi[x] = x
        if self.pi[x] != x:
            self.pi[x] = self.find(self.pi[x])
        return self.pi[x]


class Solution:
    def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:
        """
        DisjointSet? DisjointSet cannot remove connections

        Then don't add the connections from the malware at all

        For each component of G, either it neighbors 0, 1, or >= 2 nodes from
        initial. The result only changes if there is exactly 1 neighbor from
        initial, so we need a way to count this.
        """
        n = len(graph)
        initial_set = set(initial)
        normal = [i for i in range(n) if i not in initial_set]
        ds = DisjointSet()
        for i in normal:
            for j in normal:
                if graph[i][j] == 1:
                    ds.union(i, j)

        sizes = defaultdict(int)
        for i in normal:
            sizes[ds.find(i)] += 1

        comp2malcount = defaultdict(int)
        mal2comps = defaultdict(set)
        for i in normal:
            for j in initial:
                if graph[i][j] == 1:
                    comp2malcount[ds.find(i)] += 1
                    mal2comps[j].add(ds.find(i))

        idx = min(initial)
        max_size = 0
        for j in initial:
            for comp in mal2comps[j]:
                if comp2malcount[comp] == 1:
                    if sizes[comp] > max_size:
                        max_size = sizes[comp]
                        idx = j
                    elif sizes[comp] == max_size:
                        idx = min(idx, j)

        return idx
